package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketCategory;
import com.cskaoyan.market.service.MarketCategoryService;
import com.cskaoyan.market.service.impl.MarketCategoryServiceImpl;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.CategoryUpdateVo;
import com.cskaoyan.market.vo.CategoryVo;
import com.cskaoyan.market.vo.LabelValueVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;

@WebServlet("/admin/category/*")
public class AdminCategoryController extends HttpServlet {
    MarketCategoryService categoryService = new MarketCategoryServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/category/", "");
        if (op.equals("list")) {
            list(req, resp);
        } else if (op.equals("l1")) {
            l1(req, resp);
        }
    }


    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<CategoryVo> list = categoryService.list();
        Object o = ResponseUtil.okList(list);
        String resultString = JacksonUtil.getObjectMapper().writeValueAsString(o);
        resultString = resultString.replace("\"children\":null,", "").replace(",\"children\":null", "");
        resp.getWriter().println(resultString);
    }

    private void l1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<LabelValueVo> list = categoryService.l1();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.okList(list)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/category/", "");
        if (op.equals("create")) {
            create(req, resp);
        } else if (op.equals("update")) {
            update(req, resp);
        } else if (op.equals("delete")) {
            delete(req, resp);
        }
    }


    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        MarketCategory category = null;

        //进行数据校验
        try {
            category = JacksonUtil.getObjectMapper().readValue(requestBody, MarketCategory.class);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgumentValue()));
        }
        category.setAddTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setDeleted(false);
        int resCode = categoryService.create(category);
        if (resCode == 1) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(category)));
        } else {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail(-1, "类目添加失败")));
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        int result;
        try {
            MarketCategory category = objectMapper.readValue(requestBody, MarketCategory.class);
            result = categoryService.update(category);
            if (result == 0) {
                resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail()));
                return;
            }
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
        } catch (Exception e) {
            try {
                CategoryVo categoryVo = objectMapper.readValue(requestBody, CategoryVo.class);
                result = categoryService.update(categoryVo);
                if (result == 0) {
                    resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail()));
                    return;
                }
                resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
            } catch (Exception e1) {
                try {
                    CategoryUpdateVo categoryUpdateVo = objectMapper.readValue(requestBody, CategoryUpdateVo.class);
                    result = categoryService.update(categoryUpdateVo);
                    if (result == 0) {
                        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail()));
                        return;
                    }
                    resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
                } catch (Exception e2) {
                    resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
                }
            }
        }
    }


    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        String idParam = JacksonUtil.parseString(requestBody, "id");
        if (idParam.equals("") || idParam == null) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        int id = 0;
        try {
            id = Integer.parseInt(idParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        int result = categoryService.delete(id);
        if (result == 0) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.fail()));
            return;
        }
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
    }
}